// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/login_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({
    super.key,
  });

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController secondPasswordController =
      TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    userNameController.dispose();
    passwordController.dispose();
    secondPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeProvider.mainColor,
        centerTitle: true,
        title: Text('Register'.t(context)),
      ),
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Card(
              color: themeProvider.mainColor,
              child: Container(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'Welcome to register',
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: userNameController,
                      decoration: InputDecoration(
                        labelText: 'email:'.t(context),
                        hintText: 'Please input email'.t(context),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        contentPadding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: passwordController,
                      decoration: InputDecoration(
                        labelText: 'password:'.t(context),
                        hintText: 'Please input password'.t(context),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        contentPadding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                        suffixIcon: const Icon(Icons.lock),
                      ),
                      obscureText: true,
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: secondPasswordController,
                      decoration: InputDecoration(
                        labelText: 'Repeat password:'.t(context),
                        hintText: 'Please re-enter the password to confirm'.t(context),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        contentPadding: const EdgeInsets.symmetric(
                          vertical: 12,
                          horizontal: 16,
                        ),
                        suffixIcon: passwordController.text ==
                                secondPasswordController.text
                            ? const Icon(Icons.check, color: Colors.green)
                            : const Icon(Icons.close, color: Colors.red),
                      ),
                      obscureText: true,
                    ),
                    const SizedBox(height: 20),
                    Container(
                      decoration: BoxDecoration(
                        color: themeProvider.mainColor,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: TextButton(
                              onPressed: register,
                              child: Text(
                                'Register'.t(context),
                                style: const TextStyle(color: Colors.black),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> register() async {
    const url = '/register';
    if (userNameController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your username');
      return;
    }
    if (passwordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your password');
      return;
    }
    if (secondPasswordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please re-enter your password');
      return;
    }
    var params = {
      'email': userNameController.text,
      'password': passwordController.text,
    };
    var response = await DioHttp.of(context).post(url, params, '');

    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);

    if (resString['code'] == 200) {
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) {
        return const LoginPage();
      }));
    }
  }
}

class UserModel {
  String? email;
  String? password;
  int? userId;
  /// normal、vip
  String? memberType;
  String? activeUntil;

  UserModel(
      {this.activeUntil,
      this.email,
      this.memberType,
      this.password,
      this.userId});

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['activeUntil'] = activeUntil;
    map['email'] = email;
    map['userId'] = userId;
    map['password'] = password;
    map['memberType'] = memberType;
    return map;
  }

  factory UserModel.fromJson(Map<String, dynamic> json) => UserModel()
    ..password = json['password'] as String?
    ..activeUntil = json['activeUntil'] as String?
    ..email = json['email'] as String?
    ..userId = json['userId'] as int?
    ..memberType = json['memberType'] as String?;
}
